package com.lgd.factoryattendance.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.ProjectGuideInfo;
import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.Bean.ProjectSpinner;
import com.lgd.factoryattendance.Bean.ProjectType;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.ScreenUtils;
import com.lgd.factoryattendance.Utils.StringUtil;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.adapter.ElectricGuidePdfAdapter;
import com.lgd.factoryattendance.adapter.MyAdapter;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IResponse;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;
import com.wdeo3601.pdfview.PDFView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Guide_PDF_Activity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "指导书界面：";
    LinearLayout layout_back;
    Spinner projectUnit_SP, sp_projectType;
    String ANDROID_ID;
    ImageView iv_refresh, iv_img;
    TextView   tv_no_guide_machine_pdf, tv_machine_guide_book_title;
    Button bt_PDF_view;
    private final List<ProjectSpinner> projectnameList = new ArrayList<>();  // 项目 列表
    private ListView lv_guide_book;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_pdf);
        initView();
    }

    public void initView(){
        ANDROID_ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        layout_back = findViewById(R.id.layout_back);
        layout_back.setOnClickListener(this);
        sp_projectType = findViewById(R.id.sp_projectType);
        projectUnit_SP = findViewById(R.id.projectUnit_SP);
        iv_refresh = findViewById(R.id.iv_refresh);
        iv_refresh.setOnClickListener(this);
        iv_img = findViewById(R.id.iv_img);

        lv_guide_book = findViewById(R.id.lv_guide_book);
        tv_no_guide_machine_pdf = findViewById(R.id.tv_no_guide_machine_pdf);
        tv_machine_guide_book_title = findViewById(R.id.tv_machine_guide_book_title);
        projectType();
    }

    @Override
    public void onClick(View v) {
        switch ( v.getId()){
            case R.id.layout_back:
                finish();
                break;
            case R.id.iv_refresh:
                reStartActivity();
                break;
            default:
                break;
        }
    }

    // 获取 项目分类 数据
    public List<String> projectType_list = new ArrayList<>();
    public void projectType(){
        API.projectType(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                Guide_PDF_Activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<ProjectType> projectTypeList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectType>>(){}.getType());
                        Log.d(TAG, "-----项目类型----"+projectTypeList);
                        if (projectTypeList.size() > 0){
                            projectType_list.add("选择类型");
                            for (ProjectType type : projectTypeList) {
                                projectType_list.add(type.getTypename());
                            }
                        }
                        typeSpinner();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                Log.d(TAG, "onFail: -----刷新错误------:  "+statusCode);
            }
        });
    }
    ArrayAdapter<String> typeSpinner_adapter;
    //  类型 spinner 实例化
    public void typeSpinner(){
        typeSpinner_adapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_item,projectType_list);
        sp_projectType.setAdapter(typeSpinner_adapter);
        sp_projectType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "----spinner选中类型----"+projectType_list.get(position));
                String str_spinner = projectType_list.get(position);
                projectnameList.clear();
                adapter = new MyAdapter(projectnameList, Guide_PDF_Activity.this);
                projectUnit_SP.setAdapter(adapter);
                if (str_spinner.equals("选择类型")) {
//                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目类型！！！");
                    iv_img.setVisibility(View.VISIBLE);
                    lv_guide_book.setVisibility(View.GONE);
                    tv_no_guide_machine_pdf.setVisibility(View.GONE);
                    tv_machine_guide_book_title.setVisibility(View.GONE);
                }else {
                    iv_img.setVisibility(View.GONE);
                    tv_machine_guide_book_title.setVisibility(View.VISIBLE);

                    ProjectType projectType = new ProjectType();
                    projectType.setTypename(projectType_list.get(position));
                    projectType.setSerialnumber(ANDROID_ID);
                    getStartProjectInfo(projectType);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
    public void getStartProjectInfo(ProjectType projectType){
        API.getStartProjectInfo(projectType, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                Guide_PDF_Activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagementList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType());
                        System.out.println("----123456789------"+projectManagementList);
                        projectnameList.clear();
                        if (projectManagementList.size() > 0){
                            for (ProjectManagement p : projectManagementList) {
                                projectnameList.add(new ProjectSpinner(
                                        p.getProjectid(),
                                        p.getProjectname(),
                                        p.getProductacode(),
                                        p.getInstructionName(),
                                        p.getWorkingInstructionPath()  ));
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"当前设备下没有该类型的项目，请重新选择");
                        }
                        setProject(projectnameList);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    MyAdapter adapter;
    String str_projectName, str_projectACode, str_instructionName, str_workingInstructionPath;
    Long l_projectID;
    public void setProject(List<ProjectSpinner> projectnameList){
        cleanStr();
        adapter = new MyAdapter(projectnameList, Guide_PDF_Activity.this);
        projectUnit_SP.setAdapter(adapter);
        projectUnit_SP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                l_projectID = projectnameList.get(position).getProjectId();
                str_projectName = projectnameList.get(position).getProjectName();
                str_projectACode = projectnameList.get(position).getProjectACode();
                str_instructionName = projectnameList.get(position).getInstructionName();
                str_workingInstructionPath = projectnameList.get(position).getWorkingInstructionPath();

                Log.d(TAG, "---项目名称---"+str_projectName+ "---项目ID：" +l_projectID+
                        "--项目code---"+str_projectACode+
                        "---指导书名称---"+str_instructionName+
                        "---路径--"+str_workingInstructionPath   );

                // 获取 指导书 信息
                ProjectGuideInfo projectGuideInfo = new ProjectGuideInfo();
                projectGuideInfo.setProjectid(l_projectID);
                setGuideInfo(projectGuideInfo);

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    // 查找 指导书 信息
    public void setGuideInfo(ProjectGuideInfo projectGuideInfo){
        API.selectGuideInfoByEntity(projectGuideInfo, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                Guide_PDF_Activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectGuideInfo> projectGuideInfoList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectGuideInfo>>(){}.getType());
                        System.out.println("----指导书信息----"+projectGuideInfoList);
                        if (projectGuideInfoList == null || projectGuideInfoList.size() == 0){
                            setAdapterByPdf(null);
                            iv_img.setVisibility(View.VISIBLE );
                            tv_no_guide_machine_pdf.setVisibility(View.VISIBLE);
                        }else {
                            setAdapterByPdf(projectGuideInfoList);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    ElectricGuidePdfAdapter guidePdfAdapter;
    public void setAdapterByPdf(List<ProjectGuideInfo> guideInfoList){
        tv_machine_guide_book_title.setVisibility(View.VISIBLE);
        tv_no_guide_machine_pdf.setVisibility(View.GONE);
        lv_guide_book.setVisibility(View.VISIBLE);
        guidePdfAdapter = new ElectricGuidePdfAdapter(Guide_PDF_Activity.this, guideInfoList);
        lv_guide_book.setAdapter(guidePdfAdapter);
        lv_guide_book.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProjectGuideInfo projectGuideInfo = guideInfoList.get(position);
                Log.d(TAG, "listview 点击事件： ----"+projectGuideInfo);

                Intent intent = new Intent(Guide_PDF_Activity.this, PdfShowActivity.class);
                intent.putExtra("pdf_path", projectGuideInfo.getFilepath());
                intent.putExtra("pdf_name", projectGuideInfo.getFilename());
                startActivity(intent);
            }
        });
    }
    // 清空
    public void cleanStr() {
        l_projectID = null;
        str_projectName = null;
        str_projectACode =null;
        str_instructionName = null;
        str_workingInstructionPath = null;
    }

    // 重启当前页面
    private void reStartActivity() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }

    Dialog dialog;
    // dialog 查看 PDF
    private void showPdfInDialog(String pdfPath) {
        dialog = new Dialog(Guide_PDF_Activity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_pdf_viewer);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置Dialog背景透明
        int width = ScreenUtils.getWidth(Guide_PDF_Activity.this);
        dialog.getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT); // 设置Dialog大小
        dialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        dialog.show();
        //  PDF 控件设置
        try {
            PDFView pdfView = dialog.findViewById(R.id.pdfView);
            pdfView.setOffscreenPageLimit(5);
            pdfView.isCanZoom(true);
            pdfView.setMaxScale(10f);
            pdfView.showPdfFromUrl(pdfPath);
        }catch (Exception e){
            e.printStackTrace();
        }

        LinearLayout layout_back = dialog.findViewById(R.id.layout_back);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    //    弹窗 查看 PDF  popupwindow    // 暂时不用
    PopupWindow pdf_pop;
    public void showPdfInPop(String pdfPath){
        setAlpha(0.5f);
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_pdf_viewer, null);
        pdf_pop = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        pdf_pop.setFocusable(true);
//        pdf_pop.setBackgroundDrawable(new ColorDrawable());
        pdf_pop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER_HORIZONTAL, 0, 0);
        //  PDF 控件设置
        PDFView pdfView = view.findViewById(R.id.pdfView);
        pdfView.setOffscreenPageLimit(2);
        pdfView.isCanZoom(true);
        pdfView.setMaxScale(8f);
        pdfView.showPdfFromUrl(pdfPath);
        LinearLayout layout_back = view.findViewById(R.id.layout_back);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pdf_pop.dismiss();
            }
        });
        pdf_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Log.d(TAG, "onDismiss: -----弹窗关闭-----");
                setAlpha(1f);
            }
        });
    }
    //    弹窗 遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }
}